<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close @closed="$emit('closed')" align-center :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item label="采购计划单号" prop="purchase_code">
                        <el-input v-model="form.purchase_code" placeholder="采购计划单号(不填写自动生成)" clearable></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="采购计划名称" prop="plan_name">
                        <el-input v-model="form.plan_name" placeholder="请输入采购计划名称" clearable></el-input>
                    </el-form-item> -->
                </el-col>
                <el-col :span="8">
					<el-form-item label="计划日期" prop="date">
						<el-date-picker v-model="form.date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
				</el-col>
                <el-col :span="16">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="采购计划商品清单" prop="purchase_detail">
                <div class="flex">
                    <div style="display:flex;align-items:center;">
                        <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct" v-if="mode!='turn'">选择商品</el-button>
	    			    <el-button type="primary" size="small" icon="el-icon-plus" @click="checkBom">选择BOM商品</el-button>
                        <sc-import-button :auth="'goods.impoet'" :apiObj="importObj" :size="'small'" :base="base + '/file_templets/temples_bom.xls'" @importSuccess="importSuccess"></sc-import-button>
                    </div>
                    <el-form-item label="扫码录入">
                        <div style="display:flex;width:100%">
                            <el-input v-model="bar_code" ref="barInput" v-if="barInput == 0" @input="handInput"></el-input>
                            <el-switch v-model="barInput" :active-value="0" :inactive-value="1" @change="barChange"></el-switch>
                        </div>
                    </el-form-item>
                </div>
                <sc-form-table ref="table" v-model="form.purchase_detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd show-summary>
                    <el-table-column label="商品名称" align="center">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="商品编码" align="center">
                        <template #default="scope">
                            {{scope.row.goods_code}}
                        </template>
                    </el-table-column>
					<el-table-column label="商品图片" align="center">
						<template #default="scope">
							<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
						</template>
					</el-table-column>
                    <el-table-column label="规格型号" align="center">
                        <template #default="scope">
                            {{scope.row.goods_spec}}
                        </template>
                    </el-table-column>
                    <el-table-column label="分类" align="center">
                        <template #default="scope">
                            {{scope.row.cate_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" align="center">
                        <template #default="scope">
                            {{scope.row.unit_name}}
                        </template>
                    </el-table-column>
					<el-table-column label="计划数量" prop="plan_num" align="center">
						<template #default="scope">
							<el-input v-model="scope.row.plan_num" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="未税单价" align="center">
						<template #default="scope">
							<el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="含税单价" align="center">
						<template #default="scope">
                            <el-input v-model="scope.row.tax_price" placeholder="单价" @input="taxCompute" @focus="onFocus($event)"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="税率" align="center">
						<template #default="scope">
							<el-input v-model="scope.row.tax_rate" placeholder="税率" @input="taxChange" @focus="onFocus($event)"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="税额" align="center">
						<template #default="scope">
							{{ scope.row.tax_rate && scope.row.price && scope.row.plan_num ?
							(((1 + (Number(scope.row.tax_rate) / 100)) * Number(scope.row.price)* Number(scope.row.plan_num)) - ((Number(scope.row.price) * Number(scope.row.plan_num)))).toFixed(2) : 0 }}
						</template>
					</el-table-column>
                    <el-table-column label="未税合计" prop="amount" align="center"></el-table-column>
					<el-table-column label="价税合计" prop="total_price" align="center"></el-table-column>
					<el-table-column label="备注" align="center">
						<template #default="scope">
							<el-input v-model="scope.row.remark" placeholder="备注"></el-input>
						</template>
					</el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-form-item label="附件" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :is_same_name="1">
                    <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                </sc-upload-file>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
            <el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
        </template>
    </el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
    <select-bom v-if="dialog.bom" ref="bomDialog" @success="bomUpdate" @closed="dialog.bom=false"></select-bom>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
import SelectBom from '@/views/bom/selectBom.vue';
import config from '@/config'

export default {
    components: {selectGoods, SelectBom},
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增',
                mrpadd: '新增',
                sale: '新增',
                edit: '编辑',
                show: '查看',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                plan_name: "",
                purchase_code: "",
                date: this.moment().format('YYYY-MM-DD'),
                remark: "",
                enclosure: "",
                purchase_detail: [],
                is_check: 0
            },
            rules: {
                plan_name: [
                    {required: true, message: '请输入采购计划名称'}
                ],
            },
            addTemplate: {},
            dialog: {
                goods: false,
                bom: false,
            },
            applyList: [],
            taxObj: {},
            barInput: 1,
            bar_code: "",
            importObj: this.$API.goods.goods.import,
            base: config.API_URL
        }
    },
    created() {
        this.handInput = this.debounce(this.handInput, 500);
    },
    mounted() {
        // this.getApply();
        this.getIsTax()
    },
    methods: {
        // 防抖
        debounce(func, delay){
            let timeoutId;
            return function(...args) {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                timeoutId = setTimeout(() => {
                    func.apply(this, args);
                }, delay);
            };
        },
        handInput(e){
            this.getProduct(e)
        },
        async getProduct(e){
            if(!e){
                return
            }
            var res = await this.$API.goods.goods.search.get({ bar_code:e });
            let exist = this.common.isExist(res.data.id, this.form.purchase_detail, 'goods_id')
            if (exist) {
                this.form.purchase_detail.map(item1=>{
                    if(item1.goods_id == res.data.id){
                        item1.plan_num += 1
                    }
                })
            }else{
                if(res.data.id){
                    let array = []
                    array.push({
                        goods_id: res.data.id,
                        goods_name: res.data.goods_name,
                        unit_name: res.data.unit && res.data.unit.unit_name,
                        cate_name: res.data.cate && res.data.cate.cate_name,
                        goods_code: res.data.goods_code,
                        goods_spec: res.data.goods_spec,
                        goods_image: res.data.goods_image,
                        plan_num: 1,
                        price: res.data.cost_price,
					    tax_rate:this.taxObj.number,
                    })
                    this.form.purchase_detail = [...this.form.purchase_detail, ...array]
                    this.totalCompute()
                }
            }
            this.bar_code = ""
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit(e) {
            this.form.is_check = e
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.procure.plan.edit.post(this.form);
                    } else {
                        res = await this.$API.procure.plan.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.visible = false;
                        this.$emit('success', this.form, this.mode)
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
            })
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.procure.plan.detail.get({id: data.id});
            this.form.plan_name = res.data.plan_name
            this.form.purchase_code = res.data.purchase_code
            this.form.date = res.data.date
            this.form.remark = res.data.remark
            this.form.enclosure = res.data.enclosure
            let array = []
            res.data.purchase_detail.map(item => {
                array.push({
                    id: item.id,
                    goods_id: item.goods_id,
                    goods_name: item.goods && item.goods.goods_name,
                    unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                    cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
					goods_image: item.goods && item.goods.goods_image,
                    goods_code: item.goods && item.goods.goods_code,
                    goods_spec: item.goods && item.goods.goods_spec,
                    plan_num: item.plan_num,
                    price: item.price,
					amount: (Number(item.plan_num) * Number(item.price)).toFixed(2),
					tax_price: item.tax_price,
					total_price: item.total_price,
					remark: item.remark,
					tax_rate:item.tax_rate,
                })
            })
            this.form.purchase_detail = array
        },
        createSale(data) {
            let array = []
            data.map(item => {
                array.push({
                goods_id: item.goods_id,
                goods_name: item.goods_name,
                unit_name: item.unit_name,
                goods_code: item.goods_code,
                plan_num: item.plan_num,
                price: item.price,
                total_price: Number(item.plan_num) * Number(item.price),
                })
            })
            this.form.purchase_detail = array
        },
        // 选择商品
        checkProduct() {
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add')
            })
        },
        // 选择商品返回
        goodsUpdate(data) {
            let array = []
            data.map((item) => {
                array.push({
                    goods_id: item.id,
                    goods_name: item.goods_name,
                    unit_name: item.unit && item.unit.unit_name,
                    cate_name: item.cate && item.cate.cate_name,
					goods_image: item.goods_image,
                    goods_code: item.goods_code,
                    goods_spec: item.goods_spec,
                    plan_num: 1,
					tax_rate:this.taxObj.number,
                    price: item.cost_price,
                })
            })
            let existingIds = this.form.purchase_detail.map(item => item.goods_id);
            for (let i = array.length - 1; i >= 0; i--) {
                if (existingIds.includes(array[i].goods_id)) {
                array.splice(i, 1);
                }
            }
            this.form.purchase_detail = [...this.form.purchase_detail, ...array]
            this.totalCompute()
        },
        checkBom(){
            this.dialog.bom = true
            this.$nextTick(() => {
                this.$refs.bomDialog.open('add')
            })
        },
        async bomUpdate(data){
            let array = []
            data.map(item=>{
                item.bom_child.map(item1=>{
                    if(item.id == item1.bom_id){
                        array.push({
                            goods_id: item1.goods_id,
                            goods_name: item1.goods && item1.goods.goods_name,
                            unit_name: item1.goods && item1.goods.unit && item1.goods.unit.unit_name,
                            cate_name: item1.goods && item1.goods.cate && item1.goods.cate.cate_name,
							goods_image: item1.goods && item1.goods.goods_image,
                            goods_code: item1.goods && item1.goods.goods_code,
                            goods_spec: item1.goods && item1.goods.goods_spec,
                            plan_num: (Number(item.need_count) * Number(item1.number)).toFixed(2),
					        price: item1.goods && item1.goods.cost_price,
					        tax_rate:this.taxObj.number,
                            ware_id: this.ware_id ? this.ware_id : '',
                        })
                    }
                })
            })
            this.form.purchase_detail = array
            this.totalCompute()
        },
        async getIsTax() {
			var res = await this.$API.setting.getProduceTax.get();
            this.taxObj = res.data
		},
        onFocus(event) {
         event.target.select();
        },
        /**计算总金额*/
		totalCompute() {
            console.log('this.form.purchase_detail :>> ', this.form.purchase_detail);
			let count_price = 0
			this.form.total_price = 0
			this.form.purchase_detail.map(item => {
				if (item.price && item.plan_num) {
					item.total_price = (Number(item.plan_num) * Number(item.price) * (1+(Number(item.tax_rate)/100))).toFixed(2)
                    item.amount = (Number(item.plan_num) * Number(item.price)).toFixed(2)
                    item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if(this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num)/100))).toFixed(2)
			} else if(this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
		},
        taxCompute(){
            let count_price = 0
			this.form.total_price = 0
			this.form.purchase_detail.map(item => {
				if (item.price && item.plan_num) {
                    item.price = (item.tax_price / (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                    item.amount = (Number(item.plan_num) * Number(item.price)).toFixed(2)
					item.total_price = (Number(item.plan_num) * Number(item.tax_price)).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
        },
        taxChange(){
            let count_price = 0
			this.form.total_price = 0
			this.form.purchase_detail.map(item => {
				if (item.price && item.plan_num) {
                    item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
                    item.amount = (Number(item.plan_num) * Number(item.price)).toFixed(2)
					item.total_price = (Number(item.plan_num) * Number(item.price) * (1 + (Number(item.tax_rate) / 100))).toFixed(2)
					count_price = Number(count_price) + Number(item.total_price)
				}
			})
			this.form.total_price = count_price.toFixed(2)
			if (this.form.has_discount == 1) {
				this.form.total_amount = (Number(this.form.total_price) - (Number(this.form.total_price) * (Number(this.form.discount_num) / 100))).toFixed(2)
			} else if (this.form.has_discount == 2) {
				this.form.total_amount = (Number(this.form.total_price) - Number(this.form.discount_num)).toFixed(2)
			} else {
				this.form.total_amount = this.form.total_price
			}
			this.form.stages_all = []
        },
        saleCome(table) {
            this.getIsTax()
            setTimeout(()=>{
                this.form.order_id = table.id
                let array = []
                table.product.map((item) => {
                    array.push({
                        goods_id: item.goods_id,
                        goods_name: item.goods && item.goods.goods_name,
                        unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                        cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
                        goods_code: item.goods && item.goods.goods_code,
                        goods_spec: item.goods && item.goods.goods_spec,
                        plan_num: item.sale_num,
                        price: item.price,
                        tax_rate:this.taxObj && this.taxObj.number,
                        remark: item.remark,
                    })
                })
                this.form.purchase_detail = array
                this.totalCompute()
            }, 500)
        },
        barChange(e){
            if(e == 0){
                this.$nextTick(()=>{
                    this.$refs.barInput.focus()
                })
            }
        },
    }
}
</script>

<style>
.flex{
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding-right: 35px;
}
</style>
